var Util = require('../utils/util.js');
var GlobalData = require('../utils/GlobalData.js');
var Observer = [];
var app = getApp();
var buttonName = [];
/**
 * 按钮点击判断
 */
function btnObserver(btnType) {
  let obj = {};
  obj["name"] = btnType;
  buttonName.push(obj)
}
/**判断按钮是否点击过 */
function isClick(btnType) {
  var click = 0;
  for (var i = 0; i < buttonName.length; i++) {
    if (buttonName[i].name == btnType) {
      click = click + 1;
      break;
    }
  }
  if (click > 0) {
    return true
  } else {
    return false;
  }
}
/**移除按钮点击 */
function removeBtnObserver(btnType) {
  for (var i = 0; i < buttonName.length; i++) {
    if (buttonName[i].name == btnType) {
      buttonName.splice(i, 1)
    }
  }
}
/**
   * 注册观察者
   * @param name 事件名
   * @param cb 回调
   * @param context 回调作用域
   */
function rigisterObserver(name, cb, context) {
  let obj = {};
  obj["name"] = name;
  obj["cb"] = cb;
  obj["context"] = context;
  Observer.push(obj);
}
/**
 * 执行回调
 * @param name 事件名
 * @param result 执行失败为false，成功为true
 */
function ExecuteCb(name, result) {

  result = result || false;
  for (let i = 0; i < Observer.length; i++) {
    if (Observer[i]["name"] == name) {
      let cb = Observer[i]["cb"];
      let context = Observer[i]["context"];
      removeObserver(name);
      cb.call(context, result);
      break;
    }
  }
}
/**
 * 触发事件后删除该事件的观察者
 * @param name 事件名
 */
function removeObserver(name) {

  for (let i = 0; i < Observer.length; i++) {
    if (Observer[i].name == name) {
      Observer.splice(i, 1);
      i--;
    }
  }

}


/**token已过期 */
function tokenOutTime(params) {
  wx.showModal({
    title: "提示",
    content: params,
    showCancel: false,
    confirmText: "确定",
    success: function (res) {
      if (res.confirm) {
        UseNavigateTo("/pages/login/login", true)
      }
    }
  })
}


///////////////////////////////////////////////////积分商城、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、

/** */
/**获取商品分类 */
function getCategoryOfGoods() {
  OnRequestPost({ method: "getcategoryofgoods", token: app.getToken() }, getCategoryOfGoodsComplete);

}
function getCategoryOfGoodsComplete(data) {
  if (data.length > 3) {
    GlobalData.allGoods = data.slice(0, 3);
  } else {
    GlobalData.allGoods = data;
  }
  ExecuteCb("getcategoryofgoods");
}


/** */
/**获取推荐商品列表 */

function getLocalList() {
  let urlPara = { method: "getgoodsinfo", token: app.getToken(), exchangeAddress: 1, page: 1, size: 6, isrecommended: 1 }
  OnRequestPost(urlPara, getLocalListComplete);
}
function getLocalListComplete(data) {
  if (parseInt(GlobalData.productType)) {
    GlobalData.producttypeStr = "product" + GlobalData.productType;
  } else {
    GlobalData.producttypeStr = GlobalData.productType;
  }
  GlobalData.mallProductList[GlobalData.producttypeStr] = GlobalData.clone(data);
  GlobalData.GoodStyle[GlobalData.producttypeStr] = 1;
  ExecuteCb("getLocalList");
}



/**
 * 获取商品列表
 
 * index 参数1：分页（第几页）
 * size 参数2：一页有多少条数据
 * add 参数3：是否添加数据，
 *   
 * exchangeAddress 参数4：0是本地兑换 1商城兑换
 * *  categoryid 参数5：根据id获取相应的商品 
 */
function getMallProductList(index, size, add, exchangeAddress, categoryid) {
  let arg = {};
  arg["index"] = index;
  arg["size"] = size;
  arg["add"] = add;
  let urlPara;
  // if (GlobalData.mallProductList[GlobalData.producttypeStr] && GlobalData.mallProductList[GlobalData.producttypeStr].length && !add) {
  //   ExecuteCb("getMallProductList");
  // } else {
  try {
    if (categoryid) {
      urlPara = { method: "getgoodsinfo", token: app.getToken(), categoryid: categoryid, page: index, size: size }
      arg["type"] = categoryid;
    } else if (exchangeAddress < 2) {
      urlPara = { method: "getgoodsinfo", token: app.getToken(), exchangeAddress: exchangeAddress, page: index, size: size }
      arg["type"] = exchangeAddress;
    } else {
      urlPara = { method: "getgoodsinfo", token: app.getToken(), page: index, size: size }
      arg["type"] = 'all';
    }

    OnRequestPost(urlPara, onAppendEle, arg);


  } catch (error) {
    console.error("DataManagerService.getMallProductList()" + error);
  }
  // }
}


/**添加到商品列表数组数据 */
function onAppendEle(data, type) {
  if (isNaN(GlobalData.productType)) {
    GlobalData.producttypeStr = GlobalData.productType;
  } else {
    GlobalData.producttypeStr = "product" + GlobalData.productType;
  }
  if (type.add) {
    let start = (type.index - 1) * type.size;
    for (let i = 0; i < data.length; i++)
      GlobalData.mallProductList[GlobalData.producttypeStr][start + i] = GlobalData.clone(data[i]);
  }
  else
    GlobalData.mallProductList[GlobalData.producttypeStr] = GlobalData.clone(data);
  GlobalData.GoodStyle[GlobalData.producttypeStr] = type.index;
  ExecuteCb("getMallProductList");
}
/**获取购物车 */
function getShoppingCar() {
  try {
    let url = { method: "getshoppingcart", Token: app.getToken() }
    OnRequestPost(url, getshoppingcartComplete);
  } catch (error) {
    console.log(error);
  }
}
/**获取购物车成功的回调函数 */
function getshoppingcartComplete(data) {
  GlobalData.shopcarIntegral = data;
  ExecuteCb("getshoppingcart");
}

/**
  * 获取商品详情
  */
function getProductDetails(id) {
  try {
    let url = { method: "getgoodsdetails", id: id }
    OnRequestPost(url, getProductDetailsComplete);
  } catch (error) {
    console.log(error);
  }
}
function getProductDetailsComplete(data) {
  GlobalData.productDetails = data
  ExecuteCb("getgoodsdetails");
}


/**id=0添加购物车 id=其他 --修改购物车*/
function onAddCar(data) {
  try {
    // 参数3：id,必要,购物车编号,若为0表示新增，其余修改
    let url = { method: "updateshoppingcart", Token: app.getToken(), id: data.id, goodsid: data.goodsid, bonuspoints: data.bonuspoints, cash: data.cash, num: data.num }
    OnRequestPost(url, onAddCarComplete);
  } catch (error) {
    console.log(error);
  }
}
/**添加购物车或修改购物成功的回调 */
function onAddCarComplete() {
  ExecuteCb("updateshoppingcart");
}



/**获取商品总数 */
function getOrdersAllCount(state) {
  try {
    let obj = {};
    obj["state"] = state;
    let url = { method: "getorderscount", Token: app.getToken(), state: state };
    OnRequestPost(url, getOrdersAllCountComplete, obj);
  } catch (error) {
    console.log(error);
  }
}
function getOrdersAllCountComplete(data, stateArg) {
  let type = "";
  let state = parseInt(stateArg.state);
  if (state == 0) {
    type = "first";
  } else if (state == 1) {
    type = "second";
  } else if (state == 2) {
    type = "third";
  }
  GlobalData.proAllCount[type] = data.count;
  ExecuteCb("getorderscount");
}
/**兑换记录 */
function getExchangeRecordDm(id, page, size, add) {
  // state,必要,订单状态 0 未支付,1 已支付,2 已发货,3 已收货 没有state全部订单
  let obj = {};
  obj["id"] = id;
  obj["page"] = page;
  obj["size"] = size;
  obj["add"] = add;
  let url = "";
  // url = 0
  if (isNaN(id)) {
    url = { method: "getordernos", Token: app.getToken(), page: page, size: size };
    // url = this.http.getMallUrl("getordernos", "Token", GlobalData.token, "page", page, "size", size);
  } else {
    url = { method: "getordernos", Token: app.getToken(), state: id, page: page, size: size };
    // url = this.http.getMallUrl("getordernos", "Token", GlobalData.token, "page", page, "size", size, "state", id);
  }

  try {
    OnRequestPost(url, getExchangeRecordDmComplete, obj);
  } catch (error) {
    console.log(error);
  }
}
function getExchangeRecordDmComplete(data, arg) {
  let add = arg.add;
  let page = parseInt(arg.page);
  let size = parseInt(arg.size);
  let id = arg.id;
  if (add) {
    let start = (page - 1) * size;
    for (let i = 0; i < data.length; i++)
      GlobalData.exchangeRecord[id][start + i] = GlobalData.clone(data[i]);
  }
  else

    GlobalData.exchangeRecord[id] = GlobalData.clone(data);
  GlobalData.exchangeRecordPage[id] = page;
  ExecuteCb("getordernos");
}

/**提醒发货或确认收货 */
function onEditOrderDm(orderno, type) {
  try {
    let url = { method: "remindshipping", Token: app.getToken(), orderno: orderno, type: type };
    OnRequestPost(url, onEditOrderDmComplete);

  } catch (error) {
    console.log(error);
  }
}
function onEditOrderDmComplete(data) {
  ExecuteCb("remindshipping");
}

/**确认删除订单 */
function onCancelOrderDm(orderno) {
  try {
    let url = { method: "deleteordernos", Token: app.getToken(), orderno: orderno };
    OnRequestPost(url, onCancelOrderDmComplete);
  } catch (error) {
    console.log(error);
  }
}
function onCancelOrderDmComplete(data) {
  ExecuteCb("deleteordernos");
}

/**获取积分明细 */
function getIntegralRule(index, size, add) {

  let obj = {};
  obj["index"] = index
  obj["size"] = size
  obj["add"] = add
  // if (GlobalData.integralRecord.length && !add) {
  //   this.ExecuteCb("getbonuspointsflow");
  // } else {
  try {
    let url = { method: "getbonuspointsflow", Token: app.getToken(), page: index, size: size };
    OnRequestPost(url, getIntegralRuleComplete, obj);

  } catch (error) {
    console.log(error);
  }
}
function getIntegralRuleComplete(data, arg) {
  let add = arg["add"];
  let index = parseInt(arg["index"]);
  let size = parseInt(arg["size"])

  if (add) {
    let start = (index - 1) * size;
    for (let i = 0; i < data.length; i++)
      GlobalData.integralRecord[start + i] = GlobalData.clone(data[i]);
  }
  else
    for (let i = 0; i < data.length; i++) {
      GlobalData.integralRecord[i] = GlobalData.clone(data[i]);
    }
  ExecuteCb("getbonuspointsflow");
}

/**修改编辑收货地址 */
function onEditAddressDm(data) {
  //id为收货地址id
  try {
    let url = { method: "updateshippingaddress", Token: app.getToken(), id: data.id, name: data.name, phone: data.phone, areas: data.areas, address: data.address, isdefault: data.isdefault };
    OnRequestPost(url, onEditAddressDmComplete);
  } catch (error) {
    console.log(error);
  }
}
function onEditAddressDmComplete(data) {
  ExecuteCb("updateshippingaddress");
}

/**删除收货地址 */
function onDelAddressDm(id) {
  try {
    let url = { method: "deleteshippingaddress", Token: app.getToken(), id: id };
    OnRequestPost(url, onDelAddressDmComplete);

  } catch (error) {
    console.log(error);
  }
}
function onDelAddressDmComplete(data) {
  ExecuteCb("deleteshippingaddress");
}
/**修改编辑收货地址 */
function onEditAddressDm(data) {
  //id为收货地址id
  try {
    let url = { method: "updateshippingaddress", Token: app.getToken(), id: data.id, name: data.name, phone: data.phone, areas: data.areas, address: data.address, isdefault: data.isdefault };
    OnRequestPost(url, onEditAddressDmComplete);
  } catch (error) {
    console.log(error);
  }
}
function onEditAddressDmComplete(data) {
  ExecuteCb("updateshippingaddress");
}

/**获取积分商城地址 */
function getAddressData() {
  try {
    let url = { method: "getshippingaddress", Token: app.getToken() };
    OnRequestPost(url, getAddressDataComplete);
  } catch (error) {
    console.log(error);
  }
}
function getAddressDataComplete(data) {
  GlobalData.addressArr = data;
  ExecuteCb("getshippingaddress");
}
/**获取积分商城首页图 */
function getSlideshowData() {
  try {
    let url = { method: "getshop_agentBPSlideshow" };
    OnRequestPost(url, getSlideshowDataComplete);
  } catch (error) {
    console.log(error);
  }
}
function getSlideshowDataComplete(data) {
  GlobalData.picture = data;
  ExecuteCb("getshop_agentBPSlideshow");
}
/**积分抽奖记录 */
function getWinRecordDm(id, page, size, add) {
  // state, 0 自己记录,1 全部记录 state :是否获取全部记录
  let obj = {};
  obj["add"] = add;
  obj["page"] = page;
  obj["size"] = size;
  obj["id"] = id;
  try {
    let url = { method: "getdrawrecordlist", Token: app.getToken(), pageindex: page, pagesize: size, isall: id };
    OnRequestPost(url, getWinRecordDmComplete, obj);
  } catch (error) {
    console.log(error);
  }
}
function getWinRecordDmComplete(data, arg) {
  let add = arg["add"];
  let page = arg["page"];
  let size = arg["size"]
  let id = arg["id"];
  if (add) {
    let start = (page - 1) * size;
    for (let i = 0; i < data.length; i++)
      GlobalData.inteWinRecord[id][start + i] = GlobalData.clone(data[i]);
  }
  else
    // for (let i = 0; i < data.length; i++) {
    //   GlobalData.exchangeRecord[i] = GlobalData.clone(pkg.data[i]);
    // }
    GlobalData.inteWinRecord[id] = GlobalData.clone(data);

  for (let i = 0; i < GlobalData.inteWinRecord[id].length; i++) {
    //datetime
    GlobalData.inteWinRecord[id][i]["createtime"] = GlobalData.inteWinRecord[id][i]["createtime"].replace("T", " ");
    if (GlobalData.inteWinRecord[id][i]["type"] == 2) {
      if (GlobalData.inteWinRecord[id][i]["state"] == 0) {
        if (GlobalData.inteWinRecord[id][i]["isaddconsignee"]) {
          GlobalData.inteWinRecord[id][i]["ishaveAdd"] = "提醒发货"
        } else {
          GlobalData.inteWinRecord[id][i]["ishaveAdd"] = "请选择地址"
        }
      } else {
        GlobalData.inteWinRecord[id][i]["ishaveAdd"] = "已发货"
      }
      // console.log(GlobalData.inteWinRecord[id][i]["ishaveAdd"])
    } else if (GlobalData.inteWinRecord[id][i]["type"] == 3) {
      if (GlobalData.inteWinRecord[id][i]["cdkeystate"] == "未使用" || GlobalData.inteWinRecord[id][i]["cdkeystate"] == "未知") {
        GlobalData.inteWinRecord[id][i]["ishaveAdd"] = "复制";
        GlobalData.inteWinRecord[id][i]["state"] = 0
      }
      else {
        GlobalData.inteWinRecord[id][i]["ishaveAdd"] = GlobalData.inteWinRecord[id][i]["cdkeystate"];
        GlobalData.inteWinRecord[id][i]["state"] = 1
      }
    } else {
      if (GlobalData.inteWinRecord[id][i]["state"] == 0) {
        GlobalData.inteWinRecord[id][i]["ishaveAdd"] = "未发货"
      } else {
        GlobalData.inteWinRecord[id][i]["ishaveAdd"] = "已发货"
      }
    }
  }
  ExecuteCb("getdrawrecordlist");
}

function getLuckyDrawprizeConfig() {
  try {
    let url = { method: "getluckydrawprizeconfig", Token: app.getToken() };
    OnRequestPost(url, getLuckyDrawprizeConfigComplete);
  } catch (error) {
    console.log(error);
  }
}
function getLuckyDrawprizeConfigComplete(data) {
  GlobalData.prizeArr = data;
  ExecuteCb("getluckydrawprizeconfig");
}


///////////////////////////////////////////////////积分商城==================================================================================
//==============================================售卡系统=================================================================================

/**获取主页数据 */
function getHomeData() {
  GlobalData.token = app.getToken()
  let data = { method: "getagent", token: app.getToken() };
  let url = app.getRequestUrl(app.getConfig().isFormal);
  wx.request({
    url: url,
    header: {
      "Content-Type": "application/x-www-form-urlencoded"
    },
    method: "POST",
    data: Util.json2Form(data),
    complete: function (res) {
      let pkg = res.data;
      if (pkg && pkg.errcode == 0) {
        GlobalData.homeData = pkg.data;
        ExecuteCb("home")
      } else if (pkg && (pkg.errmsg == "token已过期" || pkg.errmsg == "Token 过期" || pkg.errcode == 401)) {
        tokenOutTime(pkg.errmsg);
      } else {
        if (error) {
          error.call(that)
        }
        if (pkg) {
          app.show(pkg.errmsg)
        }
      }
    }
  })
}
/**获取产品分类 */
function getKindList() {
  OnRequestPost({ method: "getproductclass", token: GlobalData.token }, onProcesskind);

}
function onProcesskind(data) {
  GlobalData.KindList = [];
  // console.log("获取产品分类", data);
  for (let i = 0; i < data.length; i++) {
    GlobalData.KindList[i] = GlobalData.clone(data[i]);
    if (GlobalData.KindList[i].gameid == GlobalData.ProListID) {
      GlobalData.KindList[i]["color"] = 'black';
      GlobalData.KindList[i]["bgcolor"] = '#ffbc7f';
      GlobalData.KindList[i]["isClick"] = true;
    } else {
      GlobalData.KindList[i]["color"] = '#999999';
      GlobalData.KindList[i]["bgcolor"] = 'white';
      GlobalData.KindList[i]["isClick"] = false;
    }
  }
  //设置第0个颜色
  if (!GlobalData.ProListID) {
    GlobalData.KindList[0]["color"] = 'black';
    GlobalData.KindList[0]["bgcolor"] = '#ffbc7f';
    GlobalData.KindList[0]["isClick"] = true;
  }

  ExecuteCb("kindtlist");
}

/**获取具体产品 */
function getProductList(index, size, gameid) {
  OnRequestPost({ method: "getproductlist", token: GlobalData.token, "pageindex": 1, "pagesize": 100, "gameid": gameid }, onProcessProductList, gameid);

}
function onProcessProductList(data, gameid) {
  let arr = [];
  for (let i = 0; i < data.length; i++) {
    arr[i] = GlobalData.clone(data[i]);
  }
  arr.sort((a, b) => {
    return a.MemberPrice - b.MemberPrice;
  });
  GlobalData.ProductList[gameid] = arr;
  GlobalData.ProListID = gameid;
  // console.log(GlobalData.ProductList[gameid], GlobalData.ProListID);
  ExecuteCb("productlist");
}

/**获取支付方式 */
function getPayType() {
  var paytypeNum = 0
  if (GlobalData.PayReason == 4) {
    paytypeNum = 3;
  } else {
    paytypeNum = GlobalData.PayReason;
  }

  OnRequestPost({ method: "getpaytype", "type": paytypeNum }, onProcessPayType);
}
function onProcessPayType(data) {
  let arr = [];
  for (let i = 0; i < data.length; i++) {
    arr[i] = {};
    arr[i] = GlobalData.clone(data[i]);
  }
  GlobalData.PayType[GlobalData.PayReason] = arr;
  // console.log(GlobalData.PayType, GlobalData.PayType[GlobalData.PayReason]);
  ExecuteCb("paytype");
}



/**获取玩家名字 */
function getPlayerName(cdFun) {
  OnRequestPost({ method: "getusernickname", "token": GlobalData.token, "uid": GlobalData.rechargeId }, onProcessPlayName, false, cdFun);

}
function onProcessPlayName(data) {
  GlobalData.PlayerName = data;
  ExecuteCb("playername");
}
/**得到俱乐部信息 */
function getClubInfo(cdFun) {
  OnRequestPost({ method: "getclub", "token": GlobalData.token, "clubid": GlobalData.clubId }, onProcessClubInfo, false, cdFun);

}

function onProcessClubInfo(data) {
  GlobalData.ClubInfo = GlobalData.clone(data);
  GlobalData.ClubName = GlobalData.ClubInfo["title"];
  GlobalData.ClubCreateName = GlobalData.ClubInfo["username"];
  // console.log(data, "俱乐部信息");
  ExecuteCb("clubinfo");
}
/**获得余额明细记录 */
function getBalanceDetail(index, size, add) {
  GlobalData.BalanceDetailother["index"] = index;
  GlobalData.BalanceDetailother["size"] = size;
  GlobalData.BalanceDetailother["add"] = add;
  if (GlobalData.BalanceDetail.length && !add)
    ExecuteCb("balancedetail");
  else {
    try {
      OnRequestPost({ method: "getamountlist", "token": GlobalData.token, "pageindex": GlobalData.BalanceDetailother["index"], "pagesize": GlobalData.BalanceDetailother["size"] }, onProcessBalance, GlobalData.BalanceDetailother);
    }
    catch (err) {
      console.error("DataManagerService.getBalanceDetail()" + err);
    }
  }
}
/**处理余额明细的数据 */
function onProcessBalance(data, otherData) {
  console.log(data);
  if (otherData["add"]) {
    let start = (otherData["index"] - 1) * otherData["size"];
    for (let i = 0; i < data.length; i++)
      GlobalData.BalanceDetail[start + i] = GlobalData.clone(data[i]);
  }
  else
    for (let i = 0; i < data.length; i++) {
      GlobalData.BalanceDetail[i] = GlobalData.clone(data[i]);
    }
  ExecuteCb("balancedetail");
}

/**获取推广收益明细 */
function getEarningDetail(index, size, add) {
  GlobalData.EarningDetailother["index"] = index,
    GlobalData.EarningDetailother["size"] = size,
    GlobalData.EarningDetailother["add"] = add
  if (GlobalData.EarningDetail.length && !add)
    ExecuteCb("earningdetail");
  else {
    try {
      OnRequestPost({ method: "getpromoterebatelist", "token": GlobalData.token, "pageindex": GlobalData.EarningDetailother["index"], "pagesize": GlobalData.EarningDetailother["size"] }, onProcessEarning, GlobalData.EarningDetailother);
    }
    catch (err) {
      console.error("DataManagerService.getEarningDetail()" + err);
    }
  }
}
/**得到推广收益后处理数据 */
function onProcessEarning(data, otherData) {
  if (otherData["add"]) {
    let start = (parseInt(otherData["index"]) - 1) * otherData["size"];
    for (let i = 0; i < data.length; i++)
      GlobalData.EarningDetail[start + i] = GlobalData.clone(data[i]);
  }
  else
    for (let i = 0; i < data.length; i++) {
      GlobalData.EarningDetail[i] = GlobalData.clone(data[i]);
    }
  ExecuteCb("earningdetail");

}

/**获取个人中心收益信息 */
function getPromoteBalance() {
  try {
    OnRequestPost({ method: "getpromoteearnings", "token": GlobalData.token }, onProcessPromoteBalance);
  }
  catch (err) {
    console.error("DataManagerService.getPromoteBalance()" + err);
  }
}
/**获取个人中心收益信息成功处理函数 */
function onProcessPromoteBalance(data, otherData) {
  GlobalData.PromoteBalance = GlobalData.clone(data);
  ExecuteCb("promotebalance");
}


/**获取购卡记录 */
function getBuyCardRecord(index, size, add) {
  GlobalData.BuyCardRecordother["index"] = index,
    GlobalData.BuyCardRecordother["size"] = size,
    GlobalData.BuyCardRecordother["add"] = add
  if (GlobalData.BuyCardRecord.length && !add) {
    ExecuteCb("buycardrecord");
  }
  else {
    try {
      OnRequestPost({ method: "getorderlist", "token": GlobalData.token, "ordertype": 0, "pageindex": GlobalData.BuyCardRecordother["index"], "pagesize": GlobalData.BuyCardRecordother["size"] }, onProcessCardRecord, GlobalData.BuyCardRecordother);
    }
    catch (err) {
      console.error("DataManagerService.getBuyCardRecord()" + err);
    }
  }
}
function onProcessCardRecord(data, otherData) {
  if (otherData["add"]) {
    let start = (parseInt(otherData["index"]) - 1) * otherData["size"];
    for (let i = 0; i < data.length; i++)
      GlobalData.BuyCardRecord[start + i] = GlobalData.clone(data[i]);
  }
  else
    for (let i = 0; i < data.length; i++) {
      GlobalData.BuyCardRecord[i] = GlobalData.clone(data[i]);
    }
  ExecuteCb("buycardrecord");
}

/**俱乐部直充记录clubrechargerecord */
function getClubRechargeRecord(index, size, add) {
  GlobalData.ClubRechargeRecordother["index"] = index,
    GlobalData.ClubRechargeRecordother["size"] = size,
    GlobalData.ClubRechargeRecordother["add"] = add
  if (GlobalData.ClubRechargeRecord.length && !add) {
    ExecuteCb("clubrechargerecord");
  }
  else {
    try {
      OnRequestPost({ method: "getorderlist", "token": GlobalData.token, "ordertype": 2, "pageindex": GlobalData.ClubRechargeRecordother["index"], "pagesize": GlobalData.ClubRechargeRecordother["size"] }, onProcessClubRechargeRecord, GlobalData.ClubRechargeRecordother);
    }
    catch (err) {
      console.error("DataManagerService.getRechargeRecord()" + err);
    }
  }

}
/** */
function onProcessClubRechargeRecord(data, otherData) {
  console.log(data);
  if (otherData["add"]) {
    let start = (parseInt(otherData["index"]) - 1) * otherData["size"];
    for (let i = 0; i < data.length; i++)
      GlobalData.ClubRechargeRecord[start + i] = GlobalData.clone(data[i]);
  }
  else
    for (let i = 0; i < data.length; i++) {
      GlobalData.ClubRechargeRecord[i] = GlobalData.clone(data[i]);
    }
  ExecuteCb("clubrechargerecord");
}

/**获取游戏直充记录 */
function getRechargeRecord(index, size, add) {
  GlobalData.RechargeRecordother["index"] = index,
    GlobalData.RechargeRecordother["size"] = size,
    GlobalData.RechargeRecordother["add"] = add
  if (GlobalData.RechargeRecord.length && !add) {
    ExecuteCb("rechargerecord");
  }
  else {
    try {
      OnRequestPost({ method: "getorderlist", "token": GlobalData.token, "ordertype": 1, "pageindex": GlobalData.RechargeRecordother["index"], "pagesize": GlobalData.RechargeRecordother["size"] }, onProcessRechargeRecord, GlobalData.RechargeRecordother);
    }
    catch (err) {
      console.error("DataManagerService.getRechargeRecord()" + err);
    }
  }
}
function onProcessRechargeRecord(data, otherData) {
  console.log(data);
  if (otherData["add"]) {
    let start = (parseInt(otherData["index"]) - 1) * otherData["size"];
    for (let i = 0; i < data.length; i++)
      GlobalData.RechargeRecord[start + i] = GlobalData.clone(data[i]);
  }
  else
    for (let i = 0; i < data.length; i++) {
      GlobalData.RechargeRecord[i] = GlobalData.clone(data[i]);
    }
  ExecuteCb("rechargerecord");
}
/**卡库取卡记录 */
/**取卡记录 */
function getGetCardRecord(index, size, add) {
  GlobalData.GetCardRecordother["index"] = index,
    GlobalData.GetCardRecordother["size"] = size,
    GlobalData.GetCardRecordother["add"] = add
  if (GlobalData.GetCardRecord.length && !add) {
    ExecuteCb("getcardrecord");
  }
  else {
    //加载中。。。。。。
    if (add) {
      //添加加载中的页面
    }
    try {

      OnRequestPost({ method: "getagentcdkeyloglist", "token": GlobalData.token, "pageindex": GlobalData.GetCardRecordother["index"], "pagesize": GlobalData.GetCardRecordother["size"] }, onProcessGetCardRecord, GlobalData.GetCardRecordother);
    }
    catch (err) {
      console.error("DataManagerService.getGetCardRecord()" + err);
    }
  }
}
function onProcessGetCardRecord(data, otherData) {
  // console.log(data);
  if (otherData["add"]) {
    let start = (parseInt(otherData["index"]) - 1) * otherData["size"];
    for (let i = 0; i < data.length; i++)
      GlobalData.GetCardRecord[start + i] = GlobalData.clone(data[i]);
  }
  else
    for (let i = 0; i < data.length; i++)
      GlobalData.GetCardRecord[i] = data[i];
  // console.log(GlobalData.GetCardRecord)
  ExecuteCb("getcardrecord");
}
/**取卡详情 */
function getGetCardDetail() {
  try {
    OnRequestPost({ method: "getagentcdkeylog", "token": GlobalData.token, "id": GlobalData.carddetail }, onProcessGetCardDetail);
  }
  catch (err) {
    console.error("DataManagerService.getGetCardDetail()" + err);
  }
}
function onProcessGetCardDetail(data) {
  GlobalData.GetCardDetail = data;
  ExecuteCb("getcarddetail");
}




/**卡库分类 */
function getDepotKind(arg, fun) {

  // if (GlobalData.DepotKind) {
  //   ExecuteCb("depotkind");
  // }
  // else {
  try {

    OnRequestPost({ method: "getagentgame", "token": GlobalData.token }, onProcessDepotKind);
  }
  catch (err) {
    console.error("DataManagerService.getDepotKind()" + err);
  }
  // }
}
function onProcessDepotKind(data) {
  GlobalData.DepotKind = [];
  for (let i = 0; i < data.length; i++)
    GlobalData.DepotKind[i] = data[i];
  // console.log("卡库分类", GlobalData.DepotKind);
  ExecuteCb("depotkind");
}


/**卡库房卡 */
function getDepotCard() {
  try {
    OnRequestPost({ method: "getcdkeycount", "token": GlobalData.token }, onProcessDepotCard);
  }
  catch (err) {
    console.error("DataManagerService.getDepotCard()" + err);
  }
}
function onProcessDepotCard(data) {
  GlobalData.DepotCard = [];
  for (let i = 0; i < data.length; i++) {
    GlobalData.DepotCard[i] = GlobalData.clone(data[i]);
    for (let j = 0; j < GlobalData.DepotKind.length; j++) {
      if (GlobalData.DepotKind[j]["gameid"] == GlobalData.DepotCard[i]["game_id"])
        GlobalData.DepotCard[i]["gamename"] = GlobalData.DepotKind[j]["title"];
    }
  }
  // console.log("卡库房卡", GlobalData.DepotCard);
  ExecuteCb("depotcard");

}
function getPromotion(year, month) {
  try {
    //     let url = "";
    var data = {};
    if (year && month)
      data = { method: "getpromoterebate", "token": GlobalData.token, "year": year, "month": month }
    else
      data = { method: "getpromoterebate", "token": GlobalData.token }
    OnRequestPost(data, onProcessPromotion);
  }
  catch (err) {
    console.error("DataManagerService.getPromotion()" + err);
  }

}
function onProcessPromotion(data) {
  // console.log(data, "日期")
  GlobalData.Promotion = GlobalData.clone(data);
  GlobalData.Promotion.list = [];
  for (let i = 0; i < data.list.length; i++) {
    GlobalData.Promotion.list[i] = data.list[i];
  }
  ExecuteCb("promotion");

}



/**获取支付方式 */
function getPayType() {
  var paytypeNum = 0
  if (GlobalData.PayReason == 4) {
    paytypeNum = 3;
  } else {
    paytypeNum = GlobalData.PayReason;
  }
  OnRequestPost({ method: "getpaytype", "type": paytypeNum }, onProcessPayType);
}
function onProcessPayType(data) {
  let arr = [];
  for (let i = 0; i < data.length; i++) {
    arr[i] = {};
    arr[i] = GlobalData.clone(data[i]);
  }
  GlobalData.PayType[GlobalData.PayReason] = arr;
  ExecuteCb("paytype");
}



/**post请求的公共部分售卡 */
function OnRequestPost(data, cb, haveArg, error) {
  var that = this;
  let url = app.getRequestUrl(app.getConfig().isFormal);
  wx.request({
    url: url,
    header: {
      "Content-Type": "application/x-www-form-urlencoded"
    },
    method: "POST",
    data: Util.json2Form(data),
    complete: function (res) {
      let pkg = res.data;
      if (pkg && pkg.errcode == 0) {
        /**请求数据成功后，处理数据的回调函数 */
        if (haveArg) {
          cb.call(that, pkg.data, haveArg);
        } else
          cb.call(that, pkg.data);
      } else if (pkg && pkg.errcode == 401) {
        GlobalData.ispay = false;
        // GlobalData.PlayerName = "";
        tokenOutTime(pkg.errmsg);

      } else {
        if (error) {
          error.call(that)
        }
        GlobalData.load = true;
        GlobalData.ispay = false;
        if (pkg) {
          app.show(pkg.errmsg, data)
        }
      }
    }
  })

}
/**获取日期函数 */
function getDate() {
  var d = new Date();
  var year = d.getFullYear();
  var month = d.getMonth() + 1;
  var date = d.getDate();
  var day = d.getDay();
  var hours = d.getHours();
  var minutes = d.getMinutes();
  var seconds = d.getSeconds();
  var ms = d.getMilliseconds();
  var curDateTime = year;
  if (month > 9)
    curDateTime = curDateTime + "-" + month;
  else
    curDateTime = curDateTime + "-0" + month;
  if (date > 9)
    curDateTime = curDateTime + "-" + date;
  else
    curDateTime = curDateTime + "-0" + date;
  curDateTime = curDateTime + " ";
  if (hours > 9)
    curDateTime = curDateTime + "" + hours;
  else
    curDateTime = curDateTime + "0" + hours;
  if (minutes > 9)
    curDateTime = curDateTime + ":" + minutes;
  else
    curDateTime = curDateTime + ":0" + minutes;
  if (seconds > 9)
    curDateTime = curDateTime + ":" + seconds;
  else
    curDateTime = curDateTime + ":0" + seconds;
  return curDateTime;
}
//==============================================售卡系统=================================================================================




/**跳转页面url:路径，isclose：是否关闭上页面 */
function UseNavigateTo(url, isClose) {
  if (isClose) {
    if (wx.reLaunch) {
      wx.reLaunch({
        url: url,
      })
    } else {
      wx.redirectTo({
        url: url,
      })
    }

  } else {
    wx.navigateTo({
      url: url
    })
  }
}

module.exports = {
  getWinRecordDm: getWinRecordDm,
  getLuckyDrawprizeConfig: getLuckyDrawprizeConfig,
  getSlideshowData: getSlideshowData,
  onDelAddressDm: onDelAddressDm,
  onEditAddressDm: onEditAddressDm,
  getAddressData: getAddressData,
  getIntegralRule: getIntegralRule,
  onCancelOrderDm: onCancelOrderDm,
  onEditOrderDm: onEditOrderDm,
  getExchangeRecordDm: getExchangeRecordDm,
  getOrdersAllCount: getOrdersAllCount,
  getAddressData: getAddressData,
  onAddCar: onAddCar,
  getProductDetails: getProductDetails,
  getShoppingCar: getShoppingCar,
  rigisterObserver: rigisterObserver,
  getMallProductList: getMallProductList,
  getLocalList: getLocalList,
  getCategoryOfGoods: getCategoryOfGoods,
  getPayType: getPayType,






  getHomeData: getHomeData,
  getKindList: getKindList,
  getProductList: getProductList,
  getPayType: getPayType,
  getPlayerName: getPlayerName,
  getClubInfo: getClubInfo,
  OnRequestPost: OnRequestPost,
  UseNavigateTo: UseNavigateTo,
  getDate: getDate,
  getBalanceDetail: getBalanceDetail,
  getEarningDetail: getEarningDetail,
  getPromoteBalance: getPromoteBalance,
  getBuyCardRecord: getBuyCardRecord,
  getClubRechargeRecord: getClubRechargeRecord,
  getRechargeRecord: getRechargeRecord,
  getGetCardRecord: getGetCardRecord,
  getGetCardDetail: getGetCardDetail,
  getDepotKind: getDepotKind,
  getDepotCard: getDepotCard,
  getPromotion: getPromotion,
  btnObserver: btnObserver,
  removeBtnObserver: removeBtnObserver,
  isClick: isClick,



}